namespace LicenseApp.Client;

/// <summary>
/// 授权状态枚举
/// </summary>
public enum LicenseStatus
{
    Valid,              // 有效
    ExpiringSoon,       // 即将到期（7天内）
    ExpiredGracePeriod, // 过期宽限期（运行中过期，1天宽限）
    Expired             // 真正过期（启动时已过期或宽限期结束）
}

/// <summary>
/// 授权信息数据结构
/// </summary>
public class LicenseInfo
{
    /// <summary>
    /// 生效开始日期
    /// </summary>
    public DateTime StartDate { get; set; }

    /// <summary>
    /// 授权天数
    /// </summary>
    public int Days { get; set; }

    /// <summary>
    /// AGV设备数量
    /// </summary>
    public int AgvCount { get; set; }

    /// <summary>
    /// 机器码（可选，为空表示不绑定机器）
    /// </summary>
    public string MachineCode { get; set; } = "";

    /// <summary>
    /// 授权结束日期
    /// </summary>
    public DateTime EndDate => StartDate.AddDays(Days);

    /// <summary>
    /// 是否在有效期内（不考虑宽限期）
    /// </summary>
    public bool IsActive
    {
        get
        {
            var now = DateTime.Now;
            return now >= StartDate && now <= EndDate;
        }
    }

    // 私有字段用于存储实际剩余天数（考虑使用天数计数器）
    private int? _actualRemainingDays = null;

    /// <summary>
    /// 剩余天数（考虑使用天数计数器）
    /// </summary>
    public int RemainingDays
    {
        get
        {
            // 如果有实际剩余天数（来自使用天数计数器），使用它
            if (_actualRemainingDays.HasValue)
                return _actualRemainingDays.Value;

            // 否则使用基于日期的计算
            var now = DateTime.Now.Date;
            if (now > EndDate.Date)
                return -1; // 已过期

            if (now < StartDate.Date)
                return Days; // 还未生效，返回总天数

            return (int)(EndDate.Date - now).TotalDays;
        }
        set
        {
            _actualRemainingDays = value;
        }
    }

    /// <summary>
    /// 是否即将到期（7天内）
    /// </summary>
    public bool IsExpiringSoon => IsActive && RemainingDays <= 7 && RemainingDays >= 0;
}

/// <summary>
/// 宽限期策略
/// </summary>
public static class LicenseGracePolicy
{
    public static readonly int GRACE_PERIOD_DAYS = 1;

    /// <summary>
    /// 判断是否有宽限期资格
    /// 只有在应用运行期间过期才有宽限期
    /// </summary>
    public static bool IsEligibleForGrace(DateTime expiryDate, DateTime applicationStartDate)
    {
        // 关键逻辑：启动时授权必须是有效的
        return applicationStartDate <= expiryDate;
    }

    /// <summary>
    /// 判断当前是否在宽限期内
    /// </summary>
    public static bool IsInGracePeriod(DateTime expiryDate, DateTime applicationStartDate)
    {
        // 首先检查是否有宽限期资格
        if (!IsEligibleForGrace(expiryDate, applicationStartDate))
            return false;

        var now = DateTime.Now;

        // 还未过期
        if (now <= expiryDate)
            return false;

        // 已过期，检查是否在1天宽限期内
        var graceEndTime = expiryDate.AddDays(GRACE_PERIOD_DAYS);
        return now <= graceEndTime;
    }

    /// <summary>
    /// 获取宽限期剩余时间
    /// </summary>
    public static TimeSpan GetRemainingGraceTime(DateTime expiryDate)
    {
        var graceEndTime = expiryDate.AddDays(GRACE_PERIOD_DAYS);
        var remaining = graceEndTime - DateTime.Now;
        return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
    }
}

/// <summary>
/// 宽限期详细信息
/// </summary>
public class GracePeriodInfo
{
    public DateTime ExpiredDate { get; set; }
    public DateTime ApplicationStartDate { get; set; }
    public DateTime GraceEndDate { get; set; }
    public bool HasGraceEligibility { get; set; }  // 是否有宽限期资格
    public TimeSpan RemainingGraceTime { get; set; }

    public bool IsExpiredToday => ExpiredDate.Date == DateTime.Now.Date;
    public int HoursInGracePeriod => Math.Max(0, (int)(DateTime.Now - ExpiredDate).TotalHours);
}

/// <summary>
/// 授权状态详细信息
/// </summary>
public class LicenseStatusInfo
{
    public LicenseStatus Status { get; set; }
    public int RemainingDays { get; set; }
    public DateTime? ExpiryDate { get; set; }
    public bool IsGracePeriod => Status == LicenseStatus.ExpiredGracePeriod;

    // 宽限期信息
    public GracePeriodInfo? GracePeriod { get; set; }

    public string Message { get; set; } = "";
    public DateTime CheckTime { get; set; }

    // 🎯 新增：详细的验证结果
    public LicenseValidationResult? ValidationResult { get; set; }

    // 🎯 新增：使用天数信息
    public int UsedDays { get; set; }

    // 🎯 新增：验证规则详情
    public ValidationRuleDetails? RuleDetails { get; set; }
}

/// <summary>
/// 验证规则详情
/// </summary>
public class ValidationRuleDetails
{
    /// <summary>
    /// 时间回拨检测结果
    /// </summary>
    public bool HasTimeRollback { get; set; }

    /// <summary>
    /// 时间停滞检测结果
    /// </summary>
    public bool HasTimeStagnation { get; set; }

    /// <summary>
    /// 停滞小时数
    /// </summary>
    public double StagnantHours { get; set; }

    /// <summary>
    /// 是否过期
    /// </summary>
    public bool IsExpired { get; set; }

    /// <summary>
    /// 过期天数
    /// </summary>
    public int ExpiredDays { get; set; }

    /// <summary>
    /// 是否提前使用
    /// </summary>
    public bool IsEarlyAccess { get; set; }

    /// <summary>
    /// 提前天数
    /// </summary>
    public int EarlyDays { get; set; }

    /// <summary>
    /// 距离生效还需等待天数
    /// </summary>
    public int DaysToWait { get; set; }

    /// <summary>
    /// 逻辑授权时间
    /// </summary>
    public DateTime LogicalLicenseDate { get; set; }

    /// <summary>
    /// 上次运行时间
    /// </summary>
    public DateTime? LastRunTime { get; set; }

    /// <summary>
    /// 首次运行时间
    /// </summary>
    public DateTime? FirstRunTime { get; set; }
}

/// <summary>
/// 授权验证结果
/// </summary>
public class LicenseValidationResult
{
    public bool IsValid { get; set; }
    public DateTime CurrentTime { get; set; }
    public int UsedDays { get; set; }
    public int RemainingDays { get; set; }
    public string Message { get; set; } = "";

    /// <summary>
    /// 详细的验证规则信息
    /// </summary>
    public ValidationRuleDetails? RuleDetails { get; set; }
}
